package com.buba.service.shuju;

import com.buba.dao.ItemMapper;
import com.buba.dao.PlanMapper;
import com.buba.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service("shujuService")
public class ShujuServiceImpl implements ShujuService{
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    PlanMapper planMapper;
    @Override
    public List<Data> listData(Integer role, Dates dates) {
        List<Item> itemList=new ArrayList<>(16);
        List<Plan> planList=new ArrayList<>(16);
        if(role==3) {
            itemList = itemMapper.listItemByDept(dates);
            planList = itemMapper.listPlanByDept(dates);
        }else{
            itemList = itemMapper.listItemByArea(dates);
            planList = itemMapper.listPlanByArea(dates);
        }
        List<Data> dataList=new ArrayList<>(16);
        for(int i=0;i<itemList.size();i++){
            //遍历实绩表对象
            Item item=itemList.get(i);
            //创建一个数据对象
            Data data=new Data();
            //往data对象里存储数据（实际表）
            if(role==3){
                data.setDeptname(item.getDeptname());
                data.setDeptid(item.getDeptid());
            }else{
                data.setAreaname(item.getAreaname());
                data.setAreaid(item.getAreaid());
            }
            data.setItemnum(item.getCount());
            data.setSumnewclient(item.getNewsum());
            data.setSumoldclient(item.getOldsum());
            data.setSumyxclient(item.getYxsum());
            data.setSummoney(item.getMoneysum());
            dataList.add(data);

        }
        for(int i=0;i<planList.size();i++){
            //遍历计划对象
            Plan plan=planList.get(i);
            //获取data列表里的对象
            Data data=dataList.get(i);
            //往data对象里存储数据（计划表）
            data.setPlannum(plan.getCount());
            Double rate;
            Double rate1=(double)data.getItemnum()/(double)data.getPlannum();
            if(rate1>1){
                rate=1.0;
            }else{
                rate=rate1;
            }
            data.setRate(rate);

        }
        //排序（降序）
        Collections.sort(dataList, new Comparator<Data>() {
            @Override
            public int compare(Data o1, Data o2) {
                return (int) (o2.getRate() - o1.getRate());
            }
        });
        //为执行排名赋值
        for (int i=0;i<dataList.size();i++){
            //获取data列表里的对象
            Data data=dataList.get(i);
            data.setRank(i+1);
        }
        return dataList;
    }
}
